import axios from "axios";
import jsonBig from "json-bigint";
import env from "./env";

console.log("hahaha", import.meta);

class Http {
  constructor(params) {
    console.log("系统参数", import.meta.env, import.meta.environment);
    this.baseUrl = params.baseUrl || import.meta.env.VITE_BASE_API;
    console.log("baseUrl", this.baseUrl);
    this.http = axios.create({
      baseURL: this.baseUrl,
      timeout: 6000 * 10,
    });
    this.http.interceptors.response.use(
      this.responseSuccessHandler,
      this.responseFailureHandler
    );
    this.http.interceptors.request.use(this.requestHandler);
  }

  responseSuccessHandler(response) {
    console.log("返回成功", response);

    return response.data;
  }

  responseFailureHandler(response) {
    console.log("请求失败的拦截", response);
  }

  requestHandler(request) {
    console.log("系统请求", request);
    request.headers.responseType = "application/json";
    //转变为respose之前可以处理返回的bigInt字段
    request.transformResponse = (data) => {
      const jsonHandle = jsonBig({ storeAsString: true });
      console.log(jsonHandle);
      return jsonHandle.parse(data);
      //   console.log(a);
      // return JSON.parse(a);
    };
    return request;
  }

  requestConfig(method, url, params) {
    let config = {
      url,
      method,
    };
    if (method === "get") {
      config.params = params;
    } else {
      config.data = params;
    }
    return config;
  }

  request(url, method, params) {
    // let config = { url, method, params };
    let config = this.requestConfig(method, url, params);
    return this.http.request(config);
  }

  get(url, params) {
    return this.request(url, "get", params);
  }

  post(url, params) {
    return this.request(url, "post", params);
  }
}

export default new Http({ baseUrl: "" });
